import { Vector3 } from 'three-legacy';
import { wsApi } from '@app-base/server';
import { MessageTip, S3Inst, StringUtils } from '@amcax/base';
import { ctx2 } from '@app-base/module';

/**翼型设计表单数据类型*/
export type AirFormDataLike = {
  /**最大弯度*/
  camber_max: number;
  /**最大弯度位置*/
  camber_max_pos: number;
  /**最大厚度*/
  thickness_max: number;
  /**最大厚度位置*/
  thickness_max_pos: number;
  /**前缘半径指数*/
  leading_radius_index: number;
  /**攻角*/
  lift_angle: number;
  /**马赫数*/
  mach_number: number;
  /**雷诺数*/
  reynolds_number: number;
};

/**
 * 创建翼型线
 */
const doRender = async (
  filePath: string,
  isFit: boolean,
  isPoints: boolean,
) => {
  const params = {
    t: filePath,
    curve: isFit,
    point: isPoints,
  };
  try {
    await wsApi.import2DPoints(params);

    ctx2.viewer.fitObjectView();
  } catch (e: unknown) {
    let message: string;

    if (e instanceof Error) {
      message = e.message;
    } else if (typeof e === 'string') {
      message = e;
    } else {
      message = JSON.stringify(e);
    }

    MessageTip.error(message);
  }
};

export const createAirFoilLine = async (
  pointsPos: Array<Vector3>,
  isFit: boolean,
  isPoints: boolean,
) => {
  try {
    const lines: string[] = pointsPos.map((point) => `${point.x}, ${point.y}`);
    const content = lines.join('\n');
    const filename = 'points.txt';

    const file = new File([content], filename, { type: 'text/plain' });

    const ossfile = StringUtils.randomString(10) + '.txt';
    await S3Inst.uploadFile(
      'cad',
      ossfile,
      file,
      (progress: { loaded: number; total: number }) => {
        Math.floor((progress.loaded * 100) / progress.total);
      },
      async (data: { bucket: string; path: string }) => {
        const bucket = data.bucket;
        const path = data.path;

        // 5. 调用渲染
        await doRender('s3://' + bucket + path, isFit, isPoints);
      },
    );
  } catch (err) {
    console.error(err);
  }
};

export const cmdAirfoilAPI = {
  id: 'CmdAirfoilAPI',
  initialDisabled: true,
  invoke: (data: Array<Vector3>, isFit: boolean, isPoints: boolean) =>
    createAirFoilLine(data, isFit, isPoints),
};
